package com.amoyt.project.security.handler;

import com.amoyt.project.constants.ResponseConstants;
import com.amoyt.project.domain.res.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @description: 授权失败处理器 （也即无权限）
 */
@Component
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //处理异常
//        Result result = Result.error().message("您的权限不足").code(HttpStatus.FORBIDDEN.value());
        log.error("权限不足");
        Result result = Result.error(ResponseConstants.NO_PERMISSION);
        ObjectMapper objectMapper = new ObjectMapper();
        String returnStr = objectMapper.writeValueAsString(result);
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(returnStr);
    }
}